package cn.yunhe.java.controller;

import cn.yunhe.java.object.AjaxDone;
import cn.yunhe.java.object.TableData;
import cn.yunhe.java.pojo.SysRoles;
import cn.yunhe.java.pojo.SysUser;
import cn.yunhe.java.security.user.MyPrincipal;
import cn.yunhe.java.service.RoleService;
import cn.yunhe.java.utils.DateUtils;
import cn.yunhe.java.vo.ZTreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService service;
    /**
     * 到角色列表页
     * @return
     */
    @RequestMapping("list")
    public String toList(){
        return "role/list";
    }

    /**
     * 查询角色的列表数据
     * @return
     */
    @RequestMapping("queryRoles")
    @ResponseBody
    public TableData queryRolesByCondition(String roleName,Integer roleStatus,int page,int limit){
        TableData td = service.queryRolesByCondition(roleName,roleStatus,page,limit);
        return  td;
    }

    /**
     * 到添加角色页面
     * @return
     */
    @RequestMapping("toAdd")
    public String toAdd(){
        return "role/add";
    }

    /**
     * 添加角色
     * @return
     */
    @RequestMapping("add")
    @ResponseBody
    public AjaxDone addRole(SysRoles sr, HttpServletRequest request){
        try{
            //获取当前操作的用户信息
            MyPrincipal principal = (MyPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            SysUser su = principal.getSysUser();

            sr.setCreateUser(su.getName());
            sr.setCreateDate(DateUtils.getSystemDate());
            sr.setRoleStatus(1);
            int rst = service.saveRole(sr);
            if(rst>0){
                return new AjaxDone(200,"保存成功！");
            }
        }catch(Exception e){
            e.printStackTrace();
            return new AjaxDone(300,"保存失败"+e.getMessage());
        }

        return new AjaxDone(300,"系统繁忙，请稍后重试！");
    }

    /**
     * 到修改页面
     * @param roleId
     * @return
     */
    @RequestMapping("toEdit")
    public String toEdit(Integer roleId, Model model){
        SysRoles sr = service.queryOne(roleId);
        model.addAttribute("role",sr);
        return "role/edit";
    }

    /**
     * 修改角色信息
     * @param sr
     * @param request
     * @return
     */
    @RequestMapping("doEdit")
    @ResponseBody
    public AjaxDone doEdit(SysRoles sr,HttpServletRequest request){
        try{
             sr.setUpdateDate(DateUtils.getSystemDate());
            //获取当前操作的用户信息
            MyPrincipal principal = (MyPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            SysUser su = principal.getSysUser();
             sr.setUpdateUser(su.getName());
              int rst = service.updateRoles(sr);
              if(rst>0){
                  return new AjaxDone(200,"修改成功！");
              }
          }catch (Exception e){
              e.printStackTrace();
              return new AjaxDone(300,"修改失败"+e.getMessage());
          }
        return new AjaxDone(300,"系统繁忙，请稍后重试！");
    }

    /**
     * 到授权页面
     * @return
     */
    @RequestMapping("toAuthorized")
    public String toAuthorized(@ModelAttribute("roleId") Integer roleId){
        return "role/authorized";
    }

    /**
     * 生成权限树
     * @param roleId
     * @return
     */
    @RequestMapping("queryRights")
    @ResponseBody
    public List<ZTreeNode> createTree(Integer roleId){
        List<ZTreeNode> rtnList = service.createTree(0,roleId);
        return rtnList;
    }

    /**
     * 保存权限
     * @return
     */
    @RequestMapping("saveRolesRights")
    @ResponseBody
    public AjaxDone saveRolesRights(Integer roleId, @RequestParam("rightsIds[]") String [] rightsIds ){
       try{
           int rst = service.saveRoleRights(roleId,rightsIds);

           //解决授权问题
           MyPrincipal principal = (MyPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
           SysUser su = principal.getSysUser();
           //获取security的上下文
           SecurityContext context = SecurityContextHolder.getContext();
           //获取认证对象信息
           Authentication authentication = context.getAuthentication();
           //获取授权信息
           Set<GrantedAuthority> authorities =  new HashSet<>();
           //取角色和按钮(权限)信息
           List<Map<String,String>> rolesList = service.queryAllRights(su.getId());
           //lambda表达式
           //添加设置后的权限信息
           rolesList.forEach((map) -> {
               map.forEach((k,v)->{
                   //System.out.println(k+"----------------"+v);
                   authorities.add(new SimpleGrantedAuthority(v));
               });
           });

           //直接强制修改认证后的权限信息
           UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                   principal,authentication.getCredentials(),authorities);
           result.setDetails(authentication.getDetails());
           //最后把设置好的权限信息，重新设置会Authentication对象中
           context.setAuthentication(result);

           if(rst>0)
             return  new AjaxDone(200,"授权成功！");
       }catch(Exception e){
           e.printStackTrace();
           return  new AjaxDone(300,"授权失败！");
       }
        return  new AjaxDone(300,"服务器繁忙，请稍后重试！");
    }



    /**
     * 删除角色信息
     * @return
     */
    @RequestMapping("delete/{roleId}")
    @ResponseBody
    public AjaxDone deleteRole(@PathVariable("roleId") Integer roleId){
        try{
            int rst = service.deleteRole(roleId);
            if(rst>0){
                return  new AjaxDone(200,"删除成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return  new AjaxDone(300,"删除失败");
        }
        return  new AjaxDone(300,"服务器繁忙，请稍后重试！");
    }

    /**
     * 修改角色状态
     * @return
     */
    @RequestMapping("updateRoleStatus")
    @ResponseBody
    public AjaxDone updateRoleStatus(Integer roleId, Integer roleStatus){
        try {
            int rst = service.updateRoleStatus(roleId, roleStatus);
            if (rst > 0) {
                return new AjaxDone(200, "状态修改成功！", null);
            }
        }catch(Exception e){
            //log4j 记录到日志文件
            return new AjaxDone(300,"Error!"+e.getMessage(),null);
        }
        return new AjaxDone(300,"Error!",null);
    }
}
